/**
 * 2017年4月25日
 */
package controllers.wechatlab;

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.bjtu.labsys.constant.Constant;
import cn.edu.bjtu.labsys.settings.ApplicationConfiguration;
import pojo.dto.sys.FileInfoDto;
import pojo.dto.sys.RuntimeInfoPair;
import pojo.jane.StudentBean;
import pojo.weichatlab.SubmittedTask;
import service.wechatlab.AdministratorService;
import service.wechatlab.SubmittedTaskService;


@Controller
@RequestMapping("admin")
public class AdministratorController extends WechatBaseController{
	@Autowired SubmittedTaskService sts;
	@Autowired AdministratorService as;
	@RequestMapping("/index.do")
	public ModelAndView index(HttpServletRequest req,HttpServletResponse res){
		HttpSession session = req.getSession();
		String name = (String) session.getAttribute(Constant.SESSION_ATTRIBUTE_NAME);
		String userid = (String)session.getAttribute(Constant.SESSION_ATTRIBUTE_USERID);
		if(name != null){
			return renderView("admin/admin", null).addObject("name", name).addObject("userid", userid);
		}
		return renderView("admin/admin", null);
	}
	@RequestMapping("/main.do")
	public ModelAndView main(HttpServletRequest req,HttpServletResponse res){
		ApplicationConfiguration appc = ApplicationConfiguration.getInstance();
		RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
		Runtime r = Runtime.getRuntime();
		List<RuntimeInfoPair> infos = new ArrayList<>();
		infos.add(new RuntimeInfoPair("JVM-Name", runtime.getVmVendor()));
		infos.add(new RuntimeInfoPair("JVM-Version", runtime.getVmVersion()));
		infos.add(new RuntimeInfoPair("Total-Mem", String.valueOf(r.totalMemory()/1000000)+"M"));
		infos.add(new RuntimeInfoPair("Free-Mem", String.valueOf(r.freeMemory()/1000000)+"M"));
		return renderView("admin/main", null).addObject("message","test message").addObject("l",appc.toPairs()).addObject("infos",infos);
	}
	@RequestMapping("/task/submitted_task.do")
	public ModelAndView tasklist(HttpServletRequest req,HttpServletResponse res){
		List<SubmittedTask> l = sts.selectTaskNew();
		List<SubmittedTask> ll = sts.selectTaskWord2vec();
		return renderView("admin/submitted_task", null).addObject("newTask",l).addObject("ll",ll);
	}
	
	@RequestMapping("/primaryuser.do")
	public ModelAndView primaryuser(HttpServletRequest req){
		List<StudentBean> stlist = as.selectAllUser();
		return renderView("admin/operation", null).addObject("student", stlist);
	}

	@ResponseBody
	@RequestMapping("/modUser.do")
	public String modUser(HttpServletRequest req, HttpServletResponse res) throws IOException {
		String newst = req.getParameter("newst");
		StudentBean st = fromJson(newst, StudentBean.class);
		if(st.getupper() == null || st.getlower() == null || st.getupper()< 0 || st.getlower() < 0 || st.getupper() < st.getlower() || st.getEmail().equals("") || st.getIdentity()==null || st.getName().equals("") || st.getPhone().equals("") || st.getUserid().equals("")){
			//res.sendRedirect("/wechat/admin/primaryuser.do");
			return jsonDump(ParamsError);
		}else 
			as.updateUser(st);
		return jsonDump(SUCCESS);
	}
	
	@RequestMapping("/welcome.do")
	public ModelAndView welcome(HttpServletRequest req){
		return renderView("admin/welcome", null);
	}
	@RequestMapping("/lda.do")
	public ModelAndView lda(HttpServletRequest req){
		return renderView("admin/lda", null);
	}
	
	
	@RequestMapping("/queryWord2vecExist.do")
	@ResponseBody
	public String queryWord2vecExist(HttpServletRequest req){
		return jsonDump(SUCCESS);
//		req.setAttribute(Constant.COMMAND_EXEC_CONTROLLER, this);
//		req.setAttribute(Constant.COMMAND_PUBLISHER, this.applicationEventPublisher);
//		req.setAttribute(Constant.COMMAND_TYPE, Constant.COMMAND_TYPE_REFLECT);
//		req.setAttribute(Constant.COMMAND_TYPE_REFLECT_KEY, "Word2VecModelQuery");
//		
//		Command command = CommandBuilder.build(req);
//		ExecuteContext tec = ExecuteContextManager.buildContext(req);
//		ExecuteResult<ModelExistQueryMessage> result = command.execute(tec);
//		if(result.isSuccess()){
//			ResCode rc = new ResCode(200, result.javaClassResult());
//			return jsonDump(rc);
//		}else{
//			String msg = result.getTipMessage();
//			ResCode rc = new ResCode(400, msg);
//			return jsonDump(rc);
//		}
	}
//	@RequestMapping("/word2vec.do")
//	public ModelAndView word2vec(HttpServletRequest req){
//		
//		req.setAttribute(Constant.COMMAND_EXEC_CONTROLLER, this);
//		req.setAttribute(Constant.COMMAND_PUBLISHER, this.applicationEventPublisher);
//		req.setAttribute(Constant.COMMAND_TYPE, Constant.COMMAND_TYPE_REFLECT);
//		req.setAttribute(Constant.COMMAND_TYPE_REFLECT_KEY, "Word2VecModelQuery");
//		
//		Command command = CommandBuilder.build(req);
//		ExecuteContext tec = ExecuteContextManager.buildContext(req);
//		//返回的结果我关心.
//		ExecuteResult<ModelExistQueryMessage> result = command.execute(tec);
//		//result.isSuccess只是决定是表示是不是成功的具体得到服务器的回复,具体显示什么还需要看模型信息.
//		if(result.isSuccess()){
//			ModelExistQueryMessage meqs = result.javaClassResult();
//			ModelInfo mi  = meqs.getModelInfo();
//			boolean isExist =  mi.getType().equals("file_mem");
//			//这里可以通过判断mi.getStatus具体的状态
//			return renderView("admin/word2vec", null)
//					.addObject("isConnected",true)
//					.addObject("isExist",isExist)
//					.addObject("modelInfo",mi);
//		}else{
//			String msg = result.getTipMessage();
//			return renderView("admin/word2vec", null)
//					.addObject("isConnected",false)
//					.addObject("msg",msg);	
//		}
//		
//	}
//	@RequestMapping("/tfidf.do")
//	public ModelAndView tfidf(HttpServletRequest req){
//		boolean isExist = ExecuteContextManager.getTFIDFContext()!=null && ExecuteContextManager.getTFIDFContext().getTotalDocCount()>0;
//		ModelAndView mv = renderView("admin/tfidf", null).addObject("isExist",isExist); 
//		if(isExist){
//			mv.addObject("docNum",ExecuteContextManager.getTFIDFContext().getTotalDocCount());
//		}
//		return  mv;
//	}
	
	@RequestMapping("/classification.do")
	public ModelAndView classification(HttpServletRequest req){
		ModelAndView mv = renderView("admin/classification", null); 
		return  mv;
	
	}
	
//	@RequestMapping("/task/dotask.do")
//	public ModelAndView buildTfidf(HttpServletRequest req){
//		//传参数用于建立Context
//		req.setAttribute(Constant.COMMAND_EXEC_CONTROLLER, this);
//		req.setAttribute(Constant.COMMAND_PUBLISHER, this.applicationEventPublisher);
//		Command command = CommandBuilder.build(req);
//		ExecuteContext tec = ExecuteContextManager.buildContext(req);
//		if(command!=null && tec!=null){
//			//返回的结果我不关心
//			ExecuteResult<?> er = command.execute(tec);
//			if(er instanceof ViewRenderExecuteResult){
//				req.setAttribute(Constant.JSP_MAP_RENDER_ATTRIBUTE, er);
//				return renderView("admin/viewTagRendered",((ViewRenderExecuteResult<?>) er).getResultMapForRender());
//			}else{
//				return renderView("admin/test", null).addObject("tip",er.getTipMessage());
//			}
//		}
//		return renderView("admin/test", null);
//	}
//	@RequestMapping(value="/display.do")
//	public ModelAndView displayDataSet(HttpServletRequest req,HttpServletResponse res) throws IOException{
//
//		List<FileInfoDto> wekafiles = listDir(getAppProperties("WEKA_FILE_DIR"));
//		List<FileInfoDto> svmdto = listDir(getAppProperties("WORD2VEC_TRANSFORMED_DIR"));
//		List<FileInfoDto>  wedto = listDir(getAppProperties("WECHAT_RAW_DATA_DIR"));
//		List<FileInfoDto>  libsvm = listDir(getAppProperties("LIBSVM_DATA_DIR"));
//		
//		Context ctx = new Context(getAppProperties("TF_IDF_DATASET_DIR"), getAppProperties("TF_IDF_RESULT_DIR"));
//		StatDriver sd = new StatDriver(ctx);
//		sd.fit();
//		return renderView("admin/dataset",null)
//				.addObject("result",wekafiles)
//				.addObject("isExist",true)
//				.addObject("totalDoc",sd.getTotalDoc())
//				.addObject("eachClassCount",sd)
//				.addObject("svmfiles",svmdto)
//				.addObject("wechatfiles",wedto)
//				.addObject("libsvm", libsvm);
//	}
	
	private List<FileInfoDto> listDir(String dir){
		File targetDir = new File(dir);
		File[] files = targetDir.listFiles();
		ArrayList<FileInfoDto>  dtos = new ArrayList<FileInfoDto>();
		for(File f : files){
			dtos.add(new FileInfoDto(f.getName(), f.length(), f.lastModified()));
		}
		return dtos;
	}
		
}
